package com.zr.daoImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.zr.dao.FunctionDaocy;
import com.zr.util.JDBCUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class FunctionDaoImplcy implements FunctionDaocy{

	/**
	 * 实现获取父节点的方法
	 */
	public JSONArray getFunctionByParentId(int parentId) {
		//创建获取功能父节点方法
		JSONArray funs= new JSONArray();
		//创建sql语句
		StringBuffer sql =new StringBuffer();
		sql.append("select* from func where pid=?");
		Connection con=JDBCUtil.getConnection();
		try {
			//获取预编译对象
			PreparedStatement pst=con.prepareStatement(sql.toString());
			pst.setInt(1, parentId);
			ResultSet rs=pst.executeQuery();
			while(rs.next()){
				//创建jsonobject对象并添加值
				JSONObject p =new JSONObject();
				p.put("id", rs.getInt("fid"));
				p.put("text", rs.getString("fname"));
				p.put("state", rs.getString("fstate"));
				 JSONObject  attr  = new JSONObject();
				attr.put("furl", rs.getString("furl"));
				 p.put("attributes", attr);
				  funs.add(p);
			}
		} catch (SQLException e) {
			
			e.printStackTrace();
			
		}
		return funs;
	}
/**
 * 实现递归调用获取父节点方法
 */
	public JSONArray getCurrentUserFuncsByParentId(int parentId) {
		JSONArray   userfuncs  = this.getFunctionByParentId(parentId);
		for (int i = 0; i < userfuncs.size(); i++) {
			  String state = userfuncs.getJSONObject(i).getString("state");
			  if("open".equals(state)){
				     continue;
			  }else{
				   int currentId = userfuncs.getJSONObject(i).getInt("id");
				   JSONArray   children  = this.getCurrentUserFuncsByParentId(currentId);
				   userfuncs.getJSONObject(i).put("children", children);
			  }
		}
		
		
		
		return  userfuncs;
	}
@Override
public int getPidByUid(int uid) {
	int fs=0;
	StringBuffer sql=new StringBuffer();
	sql.append(" SELECT role.pid FROM `role`");
	sql.append(" INNER JOIN `user` on");
	sql.append(" `user`.rid=role.rid");
	sql.append(" WHERE `user`.uid=?");
	Connection con=JDBCUtil.getConnection();
	try {
		PreparedStatement pst=con.prepareStatement(sql.toString());
		pst.setInt(1, uid);
		ResultSet rs=pst.executeQuery();
		if(rs.next()){
			fs=rs.getInt("pid");
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return fs;
}

}
